<template>
  <div class="consultation">
    <h2>车票管理</h2>
    <el-button type="primary" size="mini" @click="addData">新增</el-button>
    <div class="consultation-block">
      <div class="table" v-loading="tableLoading">
        <el-table size="mini" :data="tableDataFilter" style="width: 100%">
          <el-table-column label="序号" type="index"> </el-table-column>
          <el-table-column prop="name" label="车次"> </el-table-column>
          <el-table-column prop="startStation" label="起始站"> </el-table-column>
          <el-table-column prop="endStation" label="终点站"> </el-table-column>
          <el-table-column prop="startTime" label="起始时间" :formatter="fT1"> </el-table-column>
          <el-table-column prop="endTime" label="到达时间" :formatter="fT2"> </el-table-column>
          <el-table-column prop="type" label="类型"> </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                type="warning"
                size="mini"
                @click="updateData(scope.row)"
                >修改</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="deleteData(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pageNum"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="isVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        ref="form"
        label-width="120px"
        class="demo-form"
      >
        <el-form-item label="车次" prop="name">
          <el-input type="text" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="起始站" prop="startStation">
          <el-select v-model="form.startStation" placeholder="请选择">
            <el-option
              v-for="item in cities"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="终点站" prop="endStation">
          <el-select v-model="form.endStation" placeholder="请选择">
            <el-option
              v-for="item in cities"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到达时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型" prop="endStation">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="item in types"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="查看"
      :visible.sync="isVisible2"
      width="80%"
      :before-close="handleClose2"
    >
      <div>
        <download-excel
          class="export-excel-wrapper"
          :data="tableDataModal"
          :fields="json_fields"
          :header="title"
          :name="title + '.xls'"
        >
          <el-button size="mini" type="success">导出</el-button>
        </download-excel>
      </div>
      <div class="table">
        <el-table
          size="mini"
          :data="tableDataModal"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column
            :label="col"
            :prop="index + ''"
            :key="index"
            v-for="(col, index) in columnModel"
          >
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addTrain, getTrain, deleteTrain, updateTrain } from "../service.js";
import moment from 'moment'
export default {
  name: "home",
  mounted() {
    this.refreshTable();
  },
  data() {
    return {
      tableData: [],
      tableDataFilter: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      isVisible: false,
      dialogTitle: "",
      form: {
        name: '',
        startStation: '',
        endStation: '',
        startTime: '',
        endTime: '',
        type: '',
      },
      cities: ['北京', '上海', '南京', '广州', '重庆', '成都', '青岛'],
      types: ['动车', '高铁', '快车'],
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
        startStation: [{ required: true, message: "请输入", trigger: "blur" }],
        endStation: [{ required: true, message: "请输入", trigger: "blur" }],
        startTime: [{ required: true, message: "请输入", trigger: "blur" }],
        endTime: [{ required: true, message: "请输入", trigger: "blur" }],
        type: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      json_fields: {},
      columns: [],
      inputValue: "",
      inputVisible: false,
      isVisible2: false,
      tableDataModal: [],
      columnModel: [],
      title: "",
      funList: [],
      filter: {
        name: '',
        type: ''
      }
    };
  },
  methods: {
    naviData() {
      this.tableDataFilter = this.tableData.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageSize * this.pageNum
      );
    },
    handleAvatarSuccess(info) {
      this.form.pics.push(info.url);
    },
    getData() {
      getTrain().then((res) => {
        this.funList = res.data;
      });
    },
    handleClose() {
      this.isVisible = false;
    },
    handleClose2() {
      this.isVisible2 = false;
    },
    handleCurrentChange(index) {
      this.pageNum = index
      this.naviData()
    },
    submitForm(formName) {
      let form = {
        ...this.form
      };
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.form._id) {
            addTrain(form).then((res) => {
              if (res.code === 200) {
                this.$message.success("新增成功");
                this.isVisible = false;
                this.refreshTable();
              }
            });
            return;
          }
          let params =JSON.parse(JSON.stringify(this.form))
          delete params._id
          updateTrain(this.form._id, params).then((res) => {
            if (res.code === 200) {
              this.$message.success("编辑成功");
              this.refreshTable();
              this.isVisible = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    fT1(row) {
      return moment(row.startTime).format('YYYY-MM-DD')
    },
    fT2(row) {
      return moment(row.endTime).format('YYYY-MM-DD')
    },
    addData() {
      this.dialogTitle = "新增";
      this.isVisible = true;
      this.form = {
        name: '',
        startStation: '',
        endStation: '',
        startTime: '',
        endTime: '',
        type: '',
      };
      this.$nextTick(() => {
        this.$refs.form.resetFields()
      })
    },
    refreshTable() {
      getTrain().then((res) => {
        this.tableData = res.code === 200 ? res.data : [];
        if (this.filter.name) {
          this.tableData = this.tableData.filter(v => v.funInfo.funName.includes(this.filter.name))
        }
        if (this.filter.type) {
          this.tableData = this.tableData.filter(v => v.funInfo.types.includes(this.filter.type))
        }
        this.total = this.tableData.length;
        this.naviData()
      });
    },
    bc2() {
      this.isVisible2 = false;
    },
    detail(row) {
      this.json_fields = {};
      this.columnModel = JSON.parse(row.column);
      for (let i = 0; i < this.columnModel.length; i++) {
        this.json_fields[this.columnModel[i]] = i + "";
      }
      this.tableDataModal = JSON.parse(row.data);
      this.title = row.title;
      this.isVisible2 = true;
    },
    formatStatus(row) {
      if (row.username === "admin") {
        return "-";
      }
      if (row.data === "" || row.data === "[]") {
        return "未填写";
      } else {
        return "已填写";
      }
    },
    download() {},
    updateData(row) {
      this.form = {
        ...row,
      };
      this.dialogTitle = "修改";
      this.isVisible = true;
    },
    deleteData(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteTrain(row._id).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              if (this.tableDataFilter.length == 1) {
                this.pageNum--
              }
              this.refreshTable();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteImg(index) {
      this.form.pics.splice(index, 1);
    },
  },
};
</script>

<style scoped>
h2 {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 20px;
}
.consultation-block {
  width: 90%;
  margin-left: 5%;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  border: 1px dashed gray;
  text-align: center;
}
.avatar {
  width: 60px;
  height: 60px;
  display: block;
}
.img-blocks {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.el-icon-circle-close {
  position: absolute;
  top: -5px;
  right: -5px;
  cursor: pointer;
  color: red;
}
.filter {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
}
</style>
